<template>
    <div class="app-container">
       <!-- ECharts图表 -->
       <div class="chart-container">
        <div ref="performanceChart" style="width: 100%; height: 300px;"></div>
      </div>
  
      
     
      <!-- 查询条件 -->
      <div class="filter-container">
         <!-- 新增：用户昵称搜索 -->
        <el-input
          v-model="queryParams.query"
          placeholder="请输入用户名..."
          clearable
          style="width: 200px; margin-right: 10px;"
          @keyup.enter="fetchPerformanceData"
        />
        <el-select
          v-model="queryParams.query2"
          placeholder="选择月份"
          clearable
          style="width: 200px; margin-right: 10px;"
        >
          <el-option
            v-for="item in monthOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="fetchPerformanceData" :loading="loading">查询</el-button>
      </div>
  
     
      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%; margin-top: 20px;" v-loading="loading">
        <el-table-column prop="employeeName" label="员工姓名" align="center" />
        <el-table-column prop="department" label="部门" align="center" />
        <el-table-column prop="position" label="岗位" align="center" />
        <el-table-column prop="performanceMonth" label="绩效月份" align="center" />
        <el-table-column prop="attendanceCount" label="考勤次数" align="center" />
        <el-table-column prop="progressScore" label="进度评分" align="center" />
        <el-table-column prop="workReportCount" label="工作汇报" align="center" />
        <el-table-column prop="performanceScore" label="绩效分数" align="center" />
        <el-table-column label="绩效等级" align="center">
          <template #default="{row}">
            <el-tag :type="getLevelTagType(row.performanceLevel)">
              {{ row.performanceLevel }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </template>
  
  <script>
  import * as echarts from 'echarts'
  import requestUtil from '@/util/request'
  import { ElMessage } from 'element-plus'
  import store from '@/store'
  import { ref, onMounted } from 'vue';

  export default {
    name: 'PerformanceEvaluation',
    data() {
      return {
        loading: false,
        queryParams: {
          query: '',
          query2: ''
        },
        monthOptions: [],
        tableData: [],
        performanceChart: null
      }
    },

    created() {
      this.fetchMonthOptions() // 组件创建时获取月份选项
    },

    
    // 设置默认月份选项（备用方案）
    setDefaultMonthOptions() {
      const currentYear = new Date().getFullYear()
      this.monthOptions = Array.from({length: 12}, (_, i) => {
        const month = i + 1
        return {
          value: `${currentYear}-${month.toString().padStart(2, '0')}`,
          label: `${currentYear}年${month}月`
        }
      })
    },


    mounted() {
      this.initChart()
      this.fetchPerformanceData()
    },
methods: {

      // 获取月份选项
    async fetchMonthOptions() {
      try {
        this.monthLoading = true
        const response = await requestUtil.get('sys/jixiaokaohe/months')
        
        if (response.data.code === 200) {
          // 假设接口返回格式为: {data: ['2023-01', '2023-02', ...]}
          this.monthOptions = response.data.data.map(month => ({
            value: month,
            label: `${month.split('-')[0]}年${parseInt(month.split('-')[1])}月`
          }))
        } else {
          this.$message.error(response.data.msg || '获取月份失败')
          // 如果接口失败，使用默认值
          this.setDefaultMonthOptions()
        }
      } catch (error) {
        console.error('获取月份选项出错:', error)
        this.$message.error('获取月份选项失败')
        // 如果接口出错，使用默认值
        this.setDefaultMonthOptions()
      } finally {
        this.monthLoading = false
      }},

      // 初始化图表
      initChart() {
        this.performanceChart = echarts.init(this.$refs.performanceChart)
        window.addEventListener('resize', this.resizeChart)
      },
      
      // 调整图表大小
      resizeChart() {
        this.performanceChart && this.performanceChart.resize()
      },
      
      // 获取绩效数据
      async fetchPerformanceData() {
        const currentUser = ref(store.getters.GET_USERINFO);
        if (!currentUser.value.roles || !currentUser.value.roles.includes('超级管理员')) {
          this.queryParams.query = currentUser.value.username;
        }
        try {
          this.loading = true
          const res = await requestUtil.post("sys/jixiaokaohe/list", this.queryParams)
          this.tableData = res.data.list || []
          
          // 更新图表数据
          this.updateChartData()
        } catch (error) {
          ElMessage.error('获取数据失败: ' + (error.response?.data?.msg || error.message))
        } finally {
          this.loading = false
        }
      },
      
      // 更新图表数据
      updateChartData() {

        // 确保容器存在
    if (!this.$refs.performanceChart) {
      console.error('图表容器不存在')
      return
    }

     // 确保图表实例存在
     if (!this.performanceChart) {
      this.performanceChart = echarts.init(this.$refs.performanceChart)
      window.addEventListener('resize', this.resizeChart)
    }
    
    // 确保有数据
    if (!this.tableData || this.tableData.length === 0) {
      this.performanceChart.clear() // 清空图表
      return
    }
        
        // 按月份分组计算平均绩效分数
        const monthMap = {}
        this.tableData.forEach(item => {
          if (!monthMap[item.performanceMonth]) {
            monthMap[item.performanceMonth] = {
              count: 0,
              totalScore: 0
            }
          }
          monthMap[item.performanceMonth].count++
          monthMap[item.performanceMonth].totalScore += item.performanceScore
        })
        
        // 准备图表数据
        const months = Object.keys(monthMap).sort()
        const avgScores = months.map(month => 
          (monthMap[month].totalScore / monthMap[month].count).toFixed(2)
        )
        
        const option = {
          title: {
            text: '月度绩效考核趋势',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: params => {
              return `月份: ${params[0].name}<br/>平均绩效: ${params[0].value}`
            }
          },
          xAxis: {
            type: 'category',
            data: months,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '平均绩效分数',
            min: 0,
            max: 100
          },
          series: [{
            data: avgScores,
            type: 'line',
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(58, 77, 233, 0.8)' },
                { offset: 1, color: 'rgba(58, 77, 233, 0.1)' }
              ])
            },
            itemStyle: {
              color: '#3a4de9'
            },
            markLine: {
              silent: true,
              data: [
                { type: 'average', name: '总平均值' },
              //   { yAxis: 90, name: '优秀线' },
              //   { yAxis: 80, name: '良好线' },
              //   { yAxis: 70, name: '一般线' },
              //   { yAxis: 60, name: '合格线' }
              ]
            }
          }]
        }
        
        // 确保图表已初始化
        if (!this.performanceChart) {
        this.performanceChart = echarts.init(this.$refs.performanceChart)
        }
        this.performanceChart.setOption(option)
      },
      
      // 根据绩效等级返回不同的tag类型
      getLevelTagType(level) {
        const map = {
          '优秀': 'success',
          '良好': 'primary',
          '一般': 'warning',
          '合格': 'info',
          '不合格': 'danger'
        }
        return map[level] || ''
      }
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.resizeChart)
      this.performanceChart && this.performanceChart.dispose()
    }
  }
  </script>
  
  <style scoped>
  .app-container {
    padding: 20px;
  }
  
  .filter-container {
    margin-bottom: 20px;
  }
  
  .chart-container {
    width: 100%;
    margin-bottom: 20px;
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  </style>